
#include "../debug.h"
#include "../ems_table.h"
#include "../ems_table_callback.h"
#include "hash_table_interface.h"
#include <unistd.h>


#define HASH_TABLE_X    HASH_TABLE_LEN
#define HASH_TABLE_Y    DIGIT_U16
static table_t *hashTable[HASH_TABLE_Y][HASH_TABLE_X] = {0};
static table_t emsTable[] = EMS_TABLE;
#define EMS_TABLE_ENTRY_QTY (sizeof(emsTable) / sizeof(tableEntry_t))


tableErr_t EmsTable_Init(void)
{
    uint32_t nbrEntry;
    tableEntry_t *pEntry;
    hashTableErr_t err;

    if((err = HashTable_Create(hashTable, emsTable, EMS_TABLE_ENTRY_QTY)) != HASH_TABLE_ERR_NONE)
    {
        PRINT_ERROR("%d", err);
        return -TABLE_ERR_INIT;
    }

    for(nbrEntry = 0; nbrEntry < EMS_TABLE_ENTRY_QTY; nbrEntry++)
    {
        pEntry = &emsTable[nbrEntry];
        // if(pEntry->attr & TEA_WR)
        {
            EmsTable_InitCallback(pEntry);
        }
    }

    PRINT_INFO("Success");
    return TABLE_ERR_NONE;
}


tableErr_t EmsTable_Refresh(uint16_t msgVal)
{
    uint32_t nbrEntry;
    tableEntry_t *pEntry;

    for(nbrEntry = 0; nbrEntry < EMS_TABLE_ENTRY_QTY; nbrEntry++)
    {
        pEntry = &emsTable[nbrEntry];
        
        if((pEntry->attr & TEA_RD) && pEntry->msgVal == msgVal)
        {
            EmsTable_RefreshCallback(pEntry);
        }
    }

    return TABLE_ERR_NONE;
}


tableErr_t EmsTable_Get(uint32_t idx, uint16_t *pValue)
{
    tableEntry_t *pEntry;
    hashTableErr_t err;

    if((err = HashTable_Search(hashTable, idx, &pEntry)) != HASH_TABLE_ERR_NONE)
    {
        PRINT_WARN("Idx[%d] search failure", idx);
        return -TABLE_ERR_SEARCH;
    }

    if(pEntry->attr & TEA_RD)
    {
        *pValue = pEntry->data;
        return TABLE_ERR_NONE;
    }

    return -TABLE_ERR_NO_SUPPORT;
}


tableErr_t EmsTable_Set(uint32_t idx, uint16_t value)
{
    int retVal = 2;
    tableEntry_t *pEntry;
    hashTableErr_t err;
    uint16_t oriData;

    if((err = HashTable_Search(hashTable, idx, &pEntry)) != HASH_TABLE_ERR_NONE)
    {
        printf("[%s]: Idx[%d] search failure\n", __func__, idx);
        return -TABLE_ERR_SEARCH;
    }

    if(pEntry->attr & TEA_WR)
    {
        oriData = pEntry->data;
        pEntry->data = value;
        retVal = EmsTable_SetCallback(pEntry);
        if(retVal != 1) //1:远程模式
        {
            pEntry->data = oriData;
        }
        return TABLE_ERR_NONE;
    }

    return -TABLE_ERR_NO_SUPPORT;
}

